package com.example.springbootserve.controller;

import cn.hutool.core.collection.CollUtil;
import com.example.springbootserve.common.Result;
import com.example.springbootserve.controller.Request.CategoryPageRequest;
import com.example.springbootserve.entity.Category;
import com.example.springbootserve.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@CrossOrigin
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    ICategoryService categoryService;



    @PostMapping("/save")
    public Result save(@RequestBody Category obj) {
        categoryService.save(obj);
        return Result.success();
    }

    @PutMapping("/update")
    public Result update(@RequestBody Category obj) {
        categoryService.update(obj);
        return Result.success();
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        categoryService.deleteById(id);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        Category obj =categoryService.getById(id);
        return Result.success(obj);
    }

    @GetMapping("/list")
    public Result list() {
        List<Category> list = categoryService.list();
        return Result.success(list);
    }


    @GetMapping("/tree")
    public Result tree() {
        List<Category> list = categoryService.list();

//        list.stream().filter(v -> v.getPid() == null).collect(Collectors.toList());     //第一层
        return Result.success(createTree(null,list));
    }

    //递归方法，不断搜索子集
    private List<Category> createTree(Integer pid , List<Category> categorys) {
        List<Category> treeList = new ArrayList<>();
        for (Category category  : categorys) {
            if (pid == null) {
                if (category.getPid() == null) {
                    treeList.add(category);
                    category.setChildren(createTree(category.getId(),categorys));
                }
            }else {
                    if (pid.equals(category.getPid())) {
                        treeList.add(category);
                        category.setChildren(createTree(category.getId(), categorys));
                    }
                }
            if (CollUtil.isEmpty(category.getChildren())) {
                category.setChildren(null);
            }
        }
        return treeList;
    }

    @GetMapping("/page")
    public Result page(CategoryPageRequest pageRequest) {
        return Result.success(categoryService.page(pageRequest));
    }

}
